package com.example.micro_property_springboot.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.micro_property_springboot.pojo.SysParam;
import com.example.micro_property_springboot.mapper.SysParamMapper;
import com.example.micro_property_springboot.pojo.vo.SysParamVO;
import com.example.micro_property_springboot.service.SysParamService;
import com.example.micro_property_springboot.utils.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 系统参数服务实现
 */
@Service
public class SysParamServiceImpl extends ServiceImpl<SysParamMapper, SysParam>
        implements SysParamService {
    
    @Autowired
    private SysParamMapper sysParamMapper;
    
    // 使用ConcurrentHashMap作为内存缓存
    private final Map<String, String> paramCache = new ConcurrentHashMap<>();
    
    @Override
    @Cacheable(value = "sysParam", key = "#paramKey")
    public String getParamValue(String paramKey) {
        // 先从缓存获取
        if (paramCache.containsKey(paramKey)) {
            return paramCache.get(paramKey);
        }
        
        // 从数据库获取
        SysParam param = sysParamMapper.getByParamKey(paramKey);
        if (param != null) {
            paramCache.put(paramKey, param.getParamValue());
            return param.getParamValue();
        }
        
        return null;
    }
    
    @Override
    @Cacheable(value = "sysParam", key = "'object:' + #paramKey")
    public SysParam getParamByKey(String paramKey) {
        return sysParamMapper.getByParamKey(paramKey);
    }
    
    @Override
    public List<SysParam> getAllEditableParams() {
        return sysParamMapper.getAllEditableParams();
    }
    
    @Override
    public List<SysParam> getAllSystemParams() {
        return sysParamMapper.getAllSystemParams();
    }
    
    @Override
    @Transactional
    @CacheEvict(value = "sysParam", allEntries = true)
    public boolean updateParam(SysParamVO paramVO) {
        SysParam param = getById(paramVO.getId());
        if (param == null) {
            return false;
        }

        
        // 更新参数
        BeanUtils.copyProperties(paramVO, param);
        param.setUpdateTime(LocalDateTime.now());
        
        boolean result = updateById(param);
        if (result) {
            // 更新缓存
            paramCache.put(param.getParamKey(), param.getParamValue());
        }
        
        return result;
    }
    
    @Override
    @Transactional
    @CacheEvict(value = "sysParam", allEntries = true)
    public boolean batchUpdateParams(List<SysParamVO> paramVOs) {
        if (paramVOs == null || paramVOs.isEmpty()) {
            return true;
        }
        
        List<SysParam> params = new ArrayList<>();
        LocalDateTime now = LocalDateTime.now();
        String updateBy = SecurityUtils.getCurrentUsername();
        
        for (SysParamVO vo : paramVOs) {
            SysParam param = getById(vo.getId());
            if (param == null) {
                continue;
            }
            

            
            BeanUtils.copyProperties(vo, param);
            param.setUpdateTime(now);
            params.add(param);
        }
        
        boolean result = saveOrUpdateBatch(params);
        if (result) {
            // 更新缓存
            for (SysParam param : params) {
                paramCache.put(param.getParamKey(), param.getParamValue());
            }
        }
        
        return result;
    }
    
    @Override
    @CacheEvict(value = "sysParam", allEntries = true)
    public void refreshParamCache() {
        // 清空缓存
        paramCache.clear();
        
        // 重新加载所有参数到缓存
        List<SysParam> params = list();
        for (SysParam param : params) {
            paramCache.put(param.getParamKey(), param.getParamValue());
        }
    }
    
    @Override
    public Map<String, String> getParamMap() {
        // 如果缓存为空，先刷新缓存
        if (paramCache.isEmpty()) {
            refreshParamCache();
        }
        
        return new HashMap<>(paramCache);
    }
    
    @Override
    public boolean checkParamKeyExist(String paramKey, Long id) {
        Integer count = sysParamMapper.checkParamKeyExist(paramKey, id);
        return count != null && count > 0;
    }
    
    @Override
    public Integer getIntParam(String paramKey, Integer defaultValue) {
        String value = getParamValue(paramKey);
        if (value != null) {
            try {
                return Integer.parseInt(value);
            } catch (NumberFormatException e) {
                // 解析失败返回默认值
            }
        }
        return defaultValue;
    }
    
    @Override
    public Boolean getBooleanParam(String paramKey, Boolean defaultValue) {
        String value = getParamValue(paramKey);
        if (value != null) {
            return Boolean.parseBoolean(value);
        }
        return defaultValue;
    }
}